<?php
namespace app\gacj\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\gacj\model\Article as ArticleModel;

/**
 * 文章控制器
 * @package app\gacj\admin
 */
class Article extends Admin
{
    /**
     * 文章列表
     * @author rocky
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();

        // 排序
        $order = $this->getOrder();
        if(!$order) $order='id desc';

        // 数据列表
        $data_list = ArticleModel::where($map)->order($order)->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['title' => '标题']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['title', '文章标题', 'text'],
                ['source', '采集来源', 'text'],
                ['public_time', '发布时间', 'text'],
                ['create_time', '采集时间', 'datetime'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons(['edit', 'delete' => ['data-tips' => '删除后无法恢复。']]) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->addFilter('source')
            ->setColumnWidth([
                'id'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @author rocky
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Article');
            if(true !== $result) $this->error($result);

            $data['public_time'] = $data['public_time'] ? strtotime($data['public_time']) : time();

            if ($info = ArticleModel::create($data)) {
                // 记录行为
                action_log('article_add', 'gacj_article', $rocky['id'], UID, $data['title']);
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }

        $category_list = get_category();

        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'title', '标题'],
                ['text', 'source', '来源'],
                ['ueditor', 'content', '详情'],
                ['datetime', 'public_time', '发布时间', '不填默认当前时间'],
                ['text', 'url', '链接'],
                ['radio', 'status', '立即启用', '', ['否', '是'], 1]
            ])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 项目管理id
     * @author rocky
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Article');
            if(true !== $result) $this->error($result);

            $data['public_time'] = $data['public_time'] ? strtotime($data['public_time']) : time();

            if (ArticleModel::update($data)) {
                // 记录行为
                action_log('article_add', 'gacj_article', $id, UID, $data['title']);
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        $info = ArticleModel::get($id);

        $category_list = get_category();

        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'title', '标题'],
                ['text', 'source', '来源'],
                ['ueditor', 'content', '详情'],
                ['datetime', 'public_time', '发布时间', '不填默认当前时间'],
                ['text', 'url', '链接'],
                ['radio', 'status', '立即启用', '', ['否', '是'], 1]
            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除单页
     * @param array $record 行为日志
     * @author rocky
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用单页
     * @param array $record 行为日志
     * @author rocky
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用单页
     * @param array $record 行为日志
     * @author rocky
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置单页状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author rocky
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids          = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $article_title = ArticleModel::where('id', 'in', $ids)->column('title');
        return parent::setStatus($type, ['article_'.$type, 'gacj_article', 0, UID, implode('、', $article_title)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author rocky
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $article  = ArticleModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $article . ')，新值：(' . $value . ')';
        return parent::quickEdit(['article_edit', 'gacj_article', $id, UID, $details]);
    }
}